package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @authar by xiecong
 * @Date 2022/3/11
 * @Description
 */
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空(validation校验)
        //   size为null 或 0 设置为10
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        // 最小日期为空 设置为当前
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //3.1 如果未登录直接 返回评论回复列表
        if (user == null || apCommentRepayList == null || apCommentRepayList.size() == 0) {
            return ResponseResult.okResult(apCommentRepayList);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        List<String> commentRepayIds = apCommentRepayList.stream()
                .map(ApCommentRepay::getId)
                .collect(Collectors.toList());
        // 用户id = user.getId    commentRepayId in 集合
        Query likedCommentRepay = Query.query(Criteria
                .where("authorId").is(user.getId())
                .and("commentRepayId").in(commentRepayIds));
        // 得到当前回复列表中 ，点过赞的集合
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(likedCommentRepay, ApCommentRepayLike.class);
        //如果集合不为空
        if (apCommentRepayLikes != null && apCommentRepayLikes.size() > 0) {
            List<String> likedCommentRepayIds = apCommentRepayLikes.stream()
                    .map(ApCommentRepayLike::getCommentRepayId)
                    .collect(Collectors.toList());
            // 说明有点过赞的回复
            List<ApCommentRepayVO> apCommentRepayVoList = new ArrayList<>();
            apCommentRepayList.forEach(apCommentRepay -> {
                ApCommentRepayVO apCommentRepayVo = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
                if (likedCommentRepayIds.contains(apCommentRepay.getId())) {
                    apCommentRepayVo.setOperation((short) 0);
                }
                apCommentRepayVoList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(apCommentRepayVoList);
        }
        return ResponseResult.okResult(apCommentRepayList);
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        //  是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //  回复内容安全校验
        // 简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        //2. 根据评论id查询评论信息  检查是否存在
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if (userResult.getCode() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, userResult.getErrorMessage());
        }
        user = userResult.getData();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //回复id不能为空   operation 必须 0 或 1(注解校验)
        //校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(apCommentRepay == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query query = Query.query(Criteria
                        .where("authorId").is(user.getId())
                        .and("commentRepayId").is(apCommentRepay.getId()));
        //2. 如果是点赞  判断是否点过赞
        //点过赞提示请勿重复点赞
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (dto.getOperation() == 0) {
            if(apCommentRepayLike != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }
        }
        //未点过赞， 保存点赞信息
        ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
        apCommentLike.setAuthorId(user.getId());
        apCommentLike.setCommentRepayId(apCommentRepay.getId());
        apCommentLike.setOperation(dto.getOperation());
        mongoTemplate.save(apCommentLike);
        //并将回复信息的点赞数量字段+1
        apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
        mongoTemplate.save(apCommentRepay);
        //3. 如果是取消赞
        if(apCommentRepayLike == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"您还没有点赞");
        }
        //删除点赞信息
        mongoTemplate.remove(query, ApCommentRepayLike.class);
        //并将回复信息的点赞数量字段更新-1
        apCommentRepay.setLikes(apCommentRepay.getLikes() < 0 ? 0 : apCommentRepay.getLikes() - 1);
        mongoTemplate.save(apCommentRepay);
        //4. 返回当前回复的最新点赞数量，数据的key:  likes
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
